package org.example.translate_braille.service.impl;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.translate_braille.entity.User;
import org.example.translate_braille.entity.login.LoginDto;
import org.example.translate_braille.entity.login.LoginVo;
import org.example.translate_braille.resdata.DataEnum;
import org.example.translate_braille.resdata.X;
import org.example.translate_braille.service.LoginService;
import org.example.translate_braille.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    UserService userService;

    @Override
    public X login(LoginDto loginDto) {
        try{
            Object util = HttpRequest.get("https://api.weixin.qq.com/sns/jscode2session?appid=wxf13268367ba4aef6&secret=e70422b536f7bccf9c36c703b9d6f491&js_code="+loginDto.getCode()).execute().body();
            String[] strings = StrUtil.toString(util).split(",");
            LoginVo loginVo = new LoginVo();
            if(strings[0].indexOf("session_key") != -1){
                //不存在errCode，即正常调用
                String[] sessionKey = strings[0].split(":");
                String[] openID = StrUtil.sub(strings[1],0,-1).split(":");
                loginVo.setSessionKey(StrUtil.sub(sessionKey[1],1,-1));
                loginVo.setOpenId(StrUtil.sub(openID[1],1,-1));


                //查找用户表中是否存在信息
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda()
                        .eq(User::getOpenId,loginVo.getOpenId())
                        .eq(User::getIsDeleted,0)
                ;
                List<User> userList = userService.list(queryWrapper);
                System.out.println(userList);
                User user = new User();
                if(userList.size()==0){
                    user.setUserImg(loginDto.getImg());
                    user.setOpenId(loginVo.getOpenId());
                    user.setUserName(loginDto.getNickName());
                    System.out.println(userService.inOrUpUser(user));
                }else {
                    user.setId(userList.get(0).getId());
                    user.setOpenId(loginVo.getOpenId());
                    user.setUserName(loginDto.getNickName());
                    user.setUserImg(loginDto.getImg());
                    userService.saveOrUpdate(user);
                }

                return X.ResData(DataEnum.SUCCESS, loginVo);
            }else{
                //存在errCode，返回错误信息
                String[] errCode = strings[0].split(":");
                String[] errMsg = (strings[1]+StrUtil.sub(strings[2],0,-1)).split(":");
                loginVo.setErrCode(errCode[1]);
                loginVo.setErrMsg(errMsg[1]+":"+errMsg[2]);
                throw new Exception(loginVo.toString());
            }
        }catch (Exception e){
            return X.ResData(DataEnum.LOGIN_FAIL, Convert.toStr(e));
        }
    }

    @Override
    public X webLogin(User user) {
        try {
            //查找用户表中是否存在信息
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(User::getUserName,user.getUserName())
                    .eq(User::getIsDeleted,0)
            ;
            List<User> userList = userService.list(queryWrapper);
            if(userList.size()==0){
                return X.ResData(DataEnum.SELECT_FAIL, "没有该用户，请注册");
            }else{
                QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
                queryWrapper.lambda()
                        .eq(User::getUserName,user.getUserName())
                        .eq(User::getUserPassword,user.getUserPassword())
                        .eq(User::getIsDeleted,0)
                ;
                List<User> userList2 = userService.list(queryWrapper2);
                if(userList2.size()==0){
                    return X.ResData(DataEnum.SELECT_FAIL, "密码错误");
                }
            }

            return X.ResData(DataEnum.SUCCESS,"登录成功");
        }catch(Exception e){
            return X.ResData(DataEnum.SELECT_FAIL, Convert.toStr(e));
        }
    }


    @Override
    public X webRegister(User user) {
        try {
            //查找用户表中是否存在信息
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(User::getUserName,user.getUserName())
                    .eq(User::getUserPassword,user.getUserPassword())
                    .eq(User::getIsDeleted,0)
            ;
            List<User> userList = userService.list(queryWrapper);
            if(userList.size()==0){
                System.out.println(userService.inOrUpUser(user));
                return X.ResData(DataEnum.SUCCESS, "注册成功");
            }else{
                return X.ResData(DataEnum.SELECT_FAIL, "用户已存在");
            }
        }catch(Exception e){
            return X.ResData(DataEnum.SELECT_FAIL, Convert.toStr(e));
        }
    }
}
